package main

import (
	"context"
	"fmt"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"log"
	"os"
	"time"
)

const TIME_LAYOUT = "2006-01-02 15:04:05"
const DBDUMP_CMD_PREFIX = `/app/mongodb/bin/mongodump --uri="mongodb://tcems:Tcems_Password@10.116.55.111:27001,10.116.55.112:27002,10.116.55.113:27003/tcems" --port=27001 --username=tcems --password=Password --authenticationDatabase=tcems -d=tcems -c=FactRoute`

type FactRoute_Type struct {
	DocID         string    `bson:"_id"`
	MainWaybillNo string    `bson:"mainWaybillNo"`
	CreateTm      time.Time `bson:"createTm"`
}

func init() {
	log.Println("[Notice]Program running and trying to access the MongoDB.")
}

func main() {
	//loc, _ := time.LoadLocation("Asia/Chongqing")
	toDate := time.Date(2017, time.July, 1, 0, 0, 0, 0, time.UTC)
	endDate := time.Date(2018, time.December, 1, 0, 0, 0, 0, time.UTC)

	//var factRoutes []FactRoute_Type

	// 客户端连接
	clientOptions := options.Client().ApplyURI("mongodb://xxx:xxx@10.116.xx.xxx:27001,10.116.xx.xxx:27002,10.116.xx.xxx:27003/xxx")
	//log.Println(`mongodb://tcems:Password@10.202.42.34:27001/tcems`)

	client, err := mongo.Connect(context.TODO(), clientOptions)

	if err != nil {
		fmt.Println("mongo.Connect() ERROR:", err)
		os.Exit(1)
	}
	//ctx, cancel := context.WithTimeout(context.Background(), 2*time.Hour)
	//defer cancel()

	// 检查连接
	//err = client.Ping(context.TODO(), nil)
	//
	//if err != nil {
	//	log.Fatal("Error happened: ", err)
	//} else {
	//	log.Println("Connected to MongoDB!")
	//}

	// 打开集合
	col := client.Database("tcems").Collection("FactRoute")
	//log.Println(`client.Database("tcems").Collection("FactRoute")`)
	log.Println("Accessing collection", col.Name())

	if size, err := col.CountDocuments(context.TODO(), bson.D{}); err != nil {
		log.Fatal("Error happened: ", err)
	} else {
		log.Printf("Documents total:%d\n", size)
	}

	//遍历文档
	//cur, err := col.Find(ctx, filter)
	//if err != nil {
	//	log.Fatal(err)
	//}
	//var i int64 = 0
	//for cur.Next(ctx) {
	//	i++
	//打印
	//var result FactRoute_Type
	//err = cur.Decode(&result)
	//if err != nil {
	//	log.Fatal(err)
	//}
	//log.Println(result)

	//}
	//log.Printf("Total %d documents found.", i)

	//删除文档，直到到达toDate
	for true {
		if toDate.After(endDate) {
			break
		}
		//过滤条件
		filter := bson.M{"createTm": bson.M{"$lt": toDate}}
		delResult, err := col.DeleteMany(context.TODO(), filter)
		if err != nil {
			log.Fatal(err)
		} else {
			log.Printf("Deleted %d documents.", delResult.DeletedCount)
		}

		//将toDate将前推进24小时
		oneDay, _ := time.ParseDuration("24h")
		toDate = toDate.Add(oneDay)
		log.Println("New toDay:", toDate)
		//暂停N秒
		time.Sleep(5 * time.Second)
	}

	err = client.Disconnect(context.TODO())
	if err != nil {
		log.Fatal("Error happened: ", err)
	} else {
		log.Println("Disconnect from MongoDB!")
	}

}

// https://vkt.sh/go-mongodb-driver-cookbook/
/// mongodb://10.202.42.39:27001,10.202.42.34:27001,10.202.42.42:27001/?replicaSet=rs
